import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import * as qs from 'qs';
import { map, Subscription } from 'rxjs';
import base_url from 'src/app/http/base';
import { isIUser } from 'src/app/pojo/common';
import IUser from 'src/app/pojo/IUser';
import { UserService } from 'src/app/service/user.service';

@Component({
  selector: 'user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.scss']
})

export class UserListComponent {

  users: IUser[] | null | undefined = [];
  name: string = "";
  extraData: string = "";
  usersystemrooturl: string = base_url.usersystemrooturl;
  // 用于释放订阅
  private subscriptions: Subscription[] = [];

  constructor(private userService: UserService, private route: ActivatedRoute) { };

  // 组件初始化
  ngOnInit() {
    // 路由参数
    // this.route.params.subscribe(params => {
    //   this.name = params['name'];
    //   console.log(this.name);

    // });
   let user:IUser|null = this.userService.getUser();
   let isLoggedIn = this.userService.isLoggedIn;

   console.log(user);
   console.log(isLoggedIn);

    this.route.queryParams.subscribe(params => {
      this.name = params['name'];
      this.extraData = params['extraData'];
    });
    // 接口参数
    let payload = qs.stringify({
      name: "",
      start: 0,
      pageSize: 20,
    });
    // 通过服务读取用户列表
    // 定义一个用户列表观察者
    const subscription = this.userService.getUsers(payload).pipe(
      map((users: IUser[] | null | undefined) => {
        if (Array.isArray(users)) {
          // 对用户数组按用户名倒序排列
          const sortedUsers = users.sort((a: IUser | null | undefined, b: IUser | null | undefined) => {
            if (!a || !b) return 0;
            const aName = a.name !== null && a.name ? a.name : "";
            const bName = b.name !== null && b.name ? b.name : "";
            return bName.localeCompare(aName);
          });
          return sortedUsers;
        } else {
          // 如果 users 不是数组，则直接返回原始值
          return users;
        }
      })
    ).subscribe(
      {
        next: (users: IUser[] | null | undefined) => {
          this.users = users;
          console.log(this.users);
        },
        error: (error) => {
          console.error('Error fetching users:', error);
        },
        complete: () => console.log('Complete')
      }
    );
    this.subscriptions.push(subscription);
  }

  // 组件销毁
  ngOnDestroy(): void {
    // 释放内存订阅器
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
}
